package com.giser.testapp.lib.Socket;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.giser.testapp.lib.App.EnvApplication;
import com.giser.testapp.lib.App.GlobClass;
import com.giser.testapp.lib.Location.GeographicLocation;
import com.giser.testapp.lib.Tool.EnvLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Lss on 2017/12/15.
 */

public class ClientSocket {
    private static Socket socket=null;
    //线程监听标志位
    private boolean isListen = true;
    private BufferedReader reader =null;
    private PrintWriter output = null;
    private static ClientSocket instance=null;
    private boolean isWriteDB=false;
    public static ClientSocket getInstance() {
        if (instance == null) {
            instance = new ClientSocket();
        }
        return instance;
    }

    private ClientSocket() {
        isWriteDB=false;
        initSocket();
    }
    private void initSocket(){
        try {
            // 1、创建连接
            socket = new Socket(GlobClass.ClientSocket_IP, GlobClass.ClientSocket_Port);
            // 2、设置读流的超时时间
            socket.setSoTimeout(5000);
            //* 获取输出流 *//*
            isListen = true;
            output = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            this.startThread();
            sendAction(1);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            if(!isWriteDB) {
                mHandler.sendEmptyMessage(-1);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            if(!isWriteDB) {
                mHandler.sendEmptyMessage(-1);
            }
        }
    }
    private void resetSocket(){
        try {
            // 1、创建连接
            socket = new Socket(GlobClass.ClientSocket_IP, GlobClass.ClientSocket_Port);
            // 2、设置读流的超时时间
            socket.setSoTimeout(5000);
            //* 获取输出流 *//*
            isListen = true;
            output = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            this.startThread();
            sendAction(1);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            if(!isWriteDB) {
                mHandler.sendEmptyMessage(-1);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            if(!isWriteDB) {
                mHandler.sendEmptyMessage(-1);
            }
        }
    }
    private void startThread() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                while (isListen) {
                    if (socket == null || !socket.isConnected() || socket.isClosed() || socket.isInputShutdown()) {
                        continue;
                    }
                    try {
                        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String line = reader.readLine();
                        if (line.equals("")) {
                            continue;
                        }
                        JSONObject json = new JSONObject(line);
                        String action = json.getString("Action");
                        EnvLog.i("Action:"+ action);
                        Message msg = new Message();
                        msg.obj = action;
                        msg.what=1;
                        mHandler.sendMessage(msg);
                    } catch (IOException e) {
                        if(!isWriteDB) {
                            mHandler.sendEmptyMessage(-1);
                        }
                    } catch (JSONException e) {
                        mHandler.sendEmptyMessage(-2);
                    }
                }
            }
        };
        thread.start();
    }

    /**
     * 登录t
     * type=1 登录
     * type=0 退出
     * type=2 当前状态在线
     */
    private void sendAction(int type) {
        try {
            JSONObject param = new JSONObject();
            if(type==1){
                param.put(GlobClass.clientSocketKey_LoginIn, EnvApplication.getApplication().userID+"");
            }if(type==2){
                param.put(GlobClass.clientSocketKey_OnLine, EnvApplication.getApplication().userID+"");
            }else{
                param.put(GlobClass.clientSocketKey_LoginOut, EnvApplication.getApplication().userID+"");
            }
            if(sendMessage(param.toString())){
                EnvLog.i("send true");
            }else{
                EnvLog.i("send failed");
                if(!isWriteDB) {
                    if(type==1){
                        mHandler.sendEmptyMessage(-1);
                    }else if(type==2){
                        mHandler.sendEmptyMessage(-3);
                    }
                }
            }
        }catch (JSONException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            mHandler.sendEmptyMessage(-2);
        }
    }

    //发送位置信息
    public void sendLocationInfo(GeographicLocation geo) {
        if(isWriteDB){
            //write db
            return;
        }
        try {
            JSONObject param = new JSONObject();
            param.put(GlobClass.clientSocketKey_Message, geo);
            if(sendMessage(param.toString())){
                EnvLog.i("send true");
            }else{
                EnvLog.i("send failed");
                Message msg = new Message();
                msg.obj = geo;
                msg.what=2;
                mHandler.sendMessage(msg);
            }
        }catch (JSONException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            mHandler.sendEmptyMessage(-2);
        }
    }
    //发送消息
    private boolean sendMessage(String msg)
    {
        if (!TextUtils.isEmpty(msg) && socket != null && socket.isConnected()) {
            if (!socket.isOutputShutdown()) {
                output.println(msg);
                output.flush();
                return true;
            }
        }
        return false;
    }

    //关闭socket
    public void closeSocket()
    {
        sendAction(0);
        isListen=false;
        try
        {
            if(output!=null){
                output.close();
                output=null;
            }
            if(reader!=null){
                reader.close();
                reader=null;
            }
            if(socket!=null){
                socket.close();
                socket=null;
            }
        }
        catch (IOException e)
        {
            // handleException(e, "close exception: ");
            EnvLog.i("errjor...");
        }
        instance = null;
    }
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case -2:
                    //chatView.showDiaolg("IllegalArgumentException");
                    EnvLog.e("json error");
                    break;
                case -1:
                    //启动心跳包 记录数据库
                    isWriteDB=true;
                    startTimer(0,5);
                    //chatView.showDiaolg("UnknownHostException");
                    break;
                case 1:
                    String content = (String) msg.obj;
                    switch (content){
                        case GlobClass.serverSocketKey_CurrentStatue:
                            sendAction(1);
                            break;
                        case GlobClass.serverSocketKey_MessageBack:
                            //最后加入出入的值得标识
                            break;
                        case GlobClass.serverSocketKey_ServerClose:
                            //给出提示？
                            break;
                        default:
                            break;
                    }
                    break;
                case 2:
                    break;
                case 3:
                    if(timer != null){
                        timer.cancel();
                        // 一定设置为null，否则定时器不会被回收
                    }
                    break;
                default:
                    break;
            }
        }
    };
    private Timer timer = new Timer();
    private  TimerTask task = null;
    private void startTimer(int type,int delay){
        timer.schedule(task, delay*60000, 60*60*1000);
        if(type==1){
            task = new TimerTask() {
                @Override
                public void run() {
                    // 需要做的事:发送消息
                    sendAction(2);
                    Message message = new Message();
                    message.what = 3;
                    mHandler.sendMessage(message);
                }
            };
            timer.schedule(task, delay*60000, 60*60*1000);
        }else{
            task = new TimerTask() {
                @Override
                public void run() {
                    // 需要做的事:发送消息
                    initSocket();
                    Message message = new Message();
                    message.what = 3;
                    mHandler.sendMessage(message);
                }
            };
            timer.schedule(task, delay*60000, 60*60*1000);
        }
    }
}
